import axios from 'axios'
import useToken from '../stores/token'
import config from '../config'
import router from '../router'
import { showLoadingToast,showToast,closeToast} from 'vant'

const baseURL = config.baseURL
const service = axios.create({baseURL})

service.interceptors.request.use(config => {
    const { token } = useToken()
    showLoadingToast({
        message:'加载中...',
        forbidClick:true,
        loadingType:'spinner'
    })
    if(token) {
        config.headers.jwt = token
    }
    return config
})


service.interceptors.response.use(
    response => {
        closeToast()
        const {errno,data,errmsg} = response.data
        if(errno === 0) {
            if(errmsg !=='') {
                showToast({
                    message:errmsg,
                    type:'succes'
                })
            }
            return data || true
        } 
        showToast({
        message:errmsg,
        type:'error'
    })
    if(errno ===2) {
        router.push({name:'login'})
    }
    return false
    },
    error => {
        closeToast()
        showToast({
            message:'请求失败',
            type:'fail'
        })
        console.log(error)
    }
   
)